package cn.didi.feidi.androidorder.core;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;

import cn.didi.feidi.androidorder.OrderApplication;
import cn.didi.feidi.androidorder.io.FeidiClient;
import cn.didi.feidi.androidorder.listener.OnFeidiHandlerSessionListener;


/**
 * Created by king on 2017/7/15.
 */

public class FeidiMessageHandler extends Handler implements MessageHandler {

    /**
     * 连接失败 或会话关闭或被服务器踢了
     **/
    public final static int SESSION_CLOSE = -1;
    /**
     * 连接并建立会话成功
     **/
    public final static int SESSION_CONNECT = -2;
    /**
     * 连接或访问超时
     **/
    public final static int SESSION_TIMEOUT = -3;
    /**
     * 未绑定用户
     **/
    public final static int NOT_BANG_USER = -4;

    private final String TAG = "FeidiMessageHandler.TAG";

    private static FeidiMessageHandler FeidiMessageHandler;

    private ArrayList<OnFeidiHandlerSessionListener> mSessionListeners;

    synchronized public static FeidiMessageHandler getInstance() {
        if (FeidiMessageHandler == null)
            FeidiMessageHandler = new FeidiMessageHandler();

        return FeidiMessageHandler;
    }

    private FeidiMessageHandler() {
        super();
        mSessionListeners = new ArrayList<OnFeidiHandlerSessionListener>();
    }

    /**
     * 会话消息监听器,注册事件才能响应客户端与服务器连接的所有状态
     **/
    public void addOnFeidiHandlerSessionListener(OnFeidiHandlerSessionListener listener) {
        if (mSessionListeners == null)
            mSessionListeners = new ArrayList<OnFeidiHandlerSessionListener>();

        if (!mSessionListeners.contains(listener))
            mSessionListeners.add(listener);
    }

    /**
     * 删除会话消息监听器
     **/
    public void removeFeidiHandlerSessionListener(OnFeidiHandlerSessionListener listener) {
        if (mSessionListeners != null && mSessionListeners.contains(listener))
            mSessionListeners.remove(listener);
    }

    /**
     * 使用长连接发送数据
     *
     * @param request
     */
    public void send(String request) {
        FeidiClient.getIntenace().send(request);
    }

    /**
     * 使用HTTP发送请求
     *
     * @param request
     */
    public void send(AppActionRequest request) {
        AppActionManager.getInstance().handleRequest(request);
    }

    @Override
    synchronized public void handleMessage(Message msg) {
        super.handleMessage(msg);

        int msgId = msg.arg1;
        Object response = msg.obj;

        if (mSessionListeners != null)
            for (OnFeidiHandlerSessionListener listener : mSessionListeners) {
                notifySessionListeners(msgId, response, listener);
            }
    }

    private void notifySessionListeners(int msgId, Object response, OnFeidiHandlerSessionListener listener) {
        if (listener != null) {
            try {
                switch (msgId) {
                    case SESSION_CLOSE:
                        if (listener != null)
                            listener.onSessionClosed();
                        break;
                    case SESSION_CONNECT:
                        if (listener != null)
                            listener.onSessionConnect();
                        break;
                    case SESSION_TIMEOUT:
                        makeToast("当前网络不佳 , 请求访问超时！");
                        if (listener != null)
                            listener.onSessionTimeout();
                        break;
                    default:
                        Log.d(TAG, "向" + listener.getClass().getName() + "发送通知");
                        listener.onSessionMessage(msgId, response);
                        break;
                }
            } catch (Exception ex) {
                listener.onSessionMessageException(msgId, ex);
            }
        } else {
            Log.d(TAG, " ReceivedInterface is null , FeidiMessageHandler can not notify Some of the impl");
        }
    }

    private void sendMessage(int msgId, Object object) {
        Message msg = this.obtainMessage();

        // 消息ID 主要用于做分发
        msg.arg1 = msgId;
        msg.obj = object;
        sendMessage(msg);
    }

    @Override
    public void onException(Exception ex, int exType, int msgId, String info) {
        if (ex != null)
            Log.d(TAG, "发送请求异常或者长连接运行时出异常了  [msgId=" + msgId + " , errorMsg=" + ex.getMessage() + " , engineInfo=" + info + "]");
    }

    @Override
    public void onMessageReceived(Object... response) {
        Log.d(TAG, String.valueOf((Integer) response[0]));
        sendMessage((Integer) response[0], response[1]);
    }

    @Override
    public void onSessionClosed() {
        Log.d(TAG, "不好，链接关闭了!");
        sendMessage(SESSION_CLOSE, null);
    }

    @Override
    public void onSessionConnect() {
        //// TODO: 2017/7/17 连接成功后,就自己登录做登录
//        userLogin();
        Log.d(TAG, "不错哦，链接服务器成功!");
        sendMessage(SESSION_CONNECT, null);
    }

    @Override
    public void onSessionTimeout() {
        Log.d(TAG, "不好，访问服务器或链接服务器超时!");
        sendMessage(SESSION_TIMEOUT, null);
    }

    private void makeToast(String text) {
        Toast.makeText(OrderApplication.getContext(), text, Toast.LENGTH_SHORT).show();
    }

    /**
     * 用户登录<br />
     */
    public void userLogin() {
        FeidiClient.getIntenace().userLogin();
    }

    /**
     * 连接服务器,成功或失敗,都回调session,并重置为不是抢登关闭<br />
     */
    public void connectService() {
        FeidiClient.getIntenace().connectService();
    }

    /**
     * 关闭服务器
     */
    public void closeService() {
        FeidiClient.getIntenace().closeService();
    }

}
